package com.linwen.dataStructure.list.linkList;


/**
 * @author lin
 *
 */
public class MyLinkList {
	
	 private Node first;
	 private Node last;
	 public int size;
	 
	 //插入
	 public void insert(int index, int value) {
		 if(index<0||index>size) {
			 throw new IndexOutOfBoundsException("插入超范围");
		 }
		 //创建新增节点
		 Node newNode = new Node(value);
		 //空链表时
		 if(size==0) {
			 first = newNode;
			 last = newNode;
		 }
		 //头部插入时
		 else if(index == 0) {
			 newNode.next = first;
			 first = newNode;
		 }
		 //尾部插入
		 else if(index == size+1) {
			  last.next = newNode;
			  last = newNode;
		 }
		 //中间插入
		 else {
			 Node beforeNode = search(index-1);
			 newNode.next = beforeNode.next;
			 beforeNode.next = newNode;
		 }
		 size++;
		 
	 }

	 //删除
	 public void delete(int index) {
		if(index<0||index>size) {
			throw new IndexOutOfBoundsException("删除超范围");
		}
		Node removeNode = null;
		//删除头
		if(index==0) {
			first = first.next;
		}
		//删除尾
		else if(index == size-1) {
			 Node beforeNode  = search(index-1);
			 beforeNode.next = removeNode;
			 last = beforeNode;
		}
		//删除中间
		else {
			Node beforeNode = search(index-1);
			Node node = search(index);
			beforeNode.next = node.next;
		}
		size--;
	 }
	 //修改方法
	 public void chang(int index,int value) {
		 if(index<0||index>size) {
			 throw new IndexOutOfBoundsException("修改超范围");
		 }
		 Node node = search(index);
		 node.date = value;
	 }
	 //显示方法
	 public void show() {
		 Node current = first;
		 while(current != null) {
			 System.out.print(current.date+" ");
			 current = current.next;
		 }
	 }
	 //查找方法
	 public Node search(int index) {
		 if(index<0||index>size) {
			 throw new IndexOutOfBoundsException("查找超范围");
		 }
		 Node temp = first;
		 for(int i=0;i<index;i++) {
			 temp = first.next;
		 }
		 return temp;
	 }	 
}
